/**
 *
 * 连线角色
 *
 */

const router = require('express').Router();
const rootPath = '../../../';
const baseWS = require(rootPath + 'common/base-ws');
const baseRole = require(rootPath + 'common/base-role');
const baseFile = require(rootPath + 'common/base-file');
const fs = require('fs');
const expressWs = require('express-ws');
expressWs(router);
router
.ws('/birth', (ws, req)=>{
    console.log('ws birth api')

    let auth = req.headers['sec-websocket-protocol']
    if (!auth) {
        ws.send('无效链接');
    }
    ws.id = auth;

    ws.on('message', function (msg) {
        const uid = req.cookies.uid;
        msg = JSON.parse(msg);
        // 业务代码
        baseWS.send(ws, msg, uid);

        // 某房间是否有该角色
        baseRole.get_online_list(msg.room).then((list) => {
            console.log(list.uid_list)

            // 通知所有客户端
            // global.aWss.clients.forEach((clients) => {
            //     if (list.uid_list.includes(clients.id)) {
            //         clients.send(JSON.stringify({
            //             type: 'enter',
            //             msg: `${msg.nickname}走了起来！`
            //         }));
            //     }
            // });

            // uid数据拼装
            // baseRole.room_data_handle(list, uid, hasInfo).then(result => {

            // // 把该房间角色数据添加到全局变量
            // global.ROOM_ROLE_LISTS.push(result.room_data);
            //
            // // 原数组：去重
            // const rList = global.ROOM_ROLE_LISTS;
            // for (var i in rList) {
            //     if (rList[i].room == list.room) {
            //         // 删除原数据
            //         global.ROOM_ROLE_LISTS = rList.splice(rList.indexOf(i), 1)
            //         continue;
            //     }
            // }

            // 吐出数据
            //     spitOutData(res, result.hasInfo, nickname, uid)
        });
        // });


    })
    // const path = './online-list.txt'
    // if (!global.ONLINE_LISTS.length) {
    //     console.log('global.ONLINE_LISTS为空')
    //     baseFile.read(path).then((data) => {
    //         console.log(data)
    //         global.ONLINE_LISTS = `[${data}]`
    //         // console.log(global.ONLINE_LISTS)
    //     });
    // } else {
    //     fs.watch(path, (eventType, filename) => {
    //         console.log('online-list.txt文件内容变了')
    //         baseFile.read(path).then((data) => {
    //             global.ONLINE_LISTS = `[${data}]`
    //         });
    //     });
    // }
    // console.log(global.ONLINE_LISTS)
});

module.exports = router;
